package ua.kpi.flats.dao.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import ua.kpi.flats.dao.ClientDao;
import ua.kpi.flats.entity.Client;

@Repository("clientDao")
public class ClientDaoImpl extends HibernateDaoSupport implements ClientDao {

	@Autowired
	public ClientDaoImpl(HibernateTemplate hibernateTemplate) {
		super.setHibernateTemplate(hibernateTemplate);
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true,			       
			       isolation = Isolation.READ_COMMITTED)
	public List<Client> getClients(int from, int limit) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Client.class);
		
		criteria.addOrder(Order.asc("lastName"));
		criteria.addOrder(Order.asc("firstName"));
		criteria.addOrder(Order.asc("patronymik"));
		
		return getHibernateTemplate().findByCriteria(criteria, from, limit);		
	}
	
	@Transactional(readOnly = true,			       
		           isolation = Isolation.READ_COMMITTED)
	public long count() {		
		return DataAccessUtils.longResult(getHibernateTemplate().find("SELECT count(*) FROM Client"));
	}

	@Transactional
	public Client add(Client client) {
		client.setId((Long) getHibernateTemplate().save(client));
		return client;
	}

	@Transactional(readOnly = true,			      
			       isolation = Isolation.READ_COMMITTED)
	public boolean contains(Client client) {		 
		 long count = DataAccessUtils.longResult(getHibernateTemplate().findByNamedQuery("checkClient", 
				 client.getFirstName(), client.getLastName(),client.getPatronymik(),client.getPhone(),
				 client.getEmail()));
		 
		 if (count > 0) {
			 return true;
		 } else {
			 return false;
		 }
	}		
}
